package com.hn.sanya.demo.wx.controller;

import com.hn.sanya.demo.wx.server.MenuServer;
import com.hn.sanya.demo.wx.server.MessageServer;
import com.hn.sanya.demo.wx.util.XmlToMapUtil;
import com.hn.sanya.demo.wx.vo.message.ImageMessage;
import com.hn.sanya.demo.wx.vo.message.TextMessage;
import com.hn.sanya.demo.wx.vo.message.VideoMessage;
import com.hn.sanya.demo.wx.vo.message.VoiceMessage;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.weixin4j.WeixinException;
import org.weixin4j.spi.IMessageHandler;
import org.weixin4j.util.TokenUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 功能描述: 微信开发者接入控制器
 * @param:
 * @return:
 * @auther: lxh
 * @date: 2019/1/28
 */
@RestController
@RequestMapping("wechat")
public class WeixinJieruController{

    @Autowired
    private IMessageHandler messageHandler;


    //开发者接入微信后台验证（get）
    @RequestMapping(method = RequestMethod.GET,value = "access")
    public void validate(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //消息来源可靠性验证
        String signature = request.getParameter("signature");// 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");       // 随机数
        String echostr = request.getParameter("echostr"); //随机字符串

        //Token为weixin4j.properties中配置的Token
        String token = TokenUtil.get();

        //验证签名
        if (TokenUtil.checkSignature(token, signature, timestamp, nonce)) {
            response.getWriter().write(echostr); //随机字符串
        }
    }

    //post
    @RequestMapping(method = RequestMethod.POST,value = "access")
    public void processMsg(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException, WeixinException {

        //接收消息与响应消息
        //MessageServer.getResponseXml(request,response);
        //创建自定义菜单
        MenuServer.CreateMenu();

    }

}
